/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.service.impl;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.DataDownloadProgressIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.DataDownloadServiceIntentHolder;
import lt.marsrutai.mobile.android.cache.UpdateCacheRequest;
import lt.marsrutai.mobile.android.manager.ProgressBarManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;

/**
 * Downloads, parses and stores scope data.
 * Shows status notification while download is in progress.
 *
 * @author Martynas
 */
public class DataDownloadService extends CancelableIntentService implements ProgressBarManager {

    public static final String BROADCAST_ACTION = "lt.marsrutai.mobile.android.service.download_progress";

    private static final Logger logger = LoggerFactory.getLogger("DataDownloadService");

    private DataDownloadProgressIntentHolder broadcaseIntentHolder;
    private Handler toastHandler;

    public DataDownloadService() {
        super("DataDownloadService");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        broadcaseIntentHolder = new DataDownloadProgressIntentHolder(BROADCAST_ACTION);
        toastHandler = new Handler(getMainLooper());
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        DataDownloadServiceIntentHolder intentHolder = new DataDownloadServiceIntentHolder(intent);
        final UpdateCacheRequest request = intentHolder.getUpdateCacheRequest();

        broadcaseIntentHolder.setScopeFolder(request.getScopeFolder());
        broadcaseIntentHolder.setProgress(0);

        showToast(String.format(getString(R.string.downloading_scope_data), request.getScopeName()));

        try {
            AppContext.getDataCacheUpdater().performUpdate(request, this);
        }
        catch (Exception e) {
            // Do not clean stored data.
            logger.info("Unable to download data.", e);
            showToast(getString(R.string.downloading_scope_data_failed));

            broadcaseIntentHolder.setProgress(-1);
            sendBroadcast(broadcaseIntentHolder.getIntent());

            return;
        }

        showToast(getString(R.string.downloading_scope_data_finished));
    }

    @Override
    public void setMax(int max) {
        broadcaseIntentHolder.setMax(max);
        sendBroadcast(broadcaseIntentHolder.getIntent());
    }

    @Override
    public void setProgress(int progress) {
        broadcaseIntentHolder.setProgress(progress);
        sendBroadcast(broadcaseIntentHolder.getIntent());
    }

    private void showToast(final String message) {
        toastHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected boolean isCancelIntent(Intent intent) {
        return !new DataDownloadServiceIntentHolder(intent).getActionStart();
    }

    @Override
    protected String getRequestKey(Intent intent) {
        return new DataDownloadServiceIntentHolder(intent).getUpdateCacheRequest().getScopeFolder();
    }

}
